import Taro from "@tarojs/taro";

const envVersion = Taro.getAccountInfoSync().miniProgram.envVersion;
const HostMap = {
  develop: process.env.TARO_APP_BASE_URL_DEVELOP,
  trial: process.env.TARO_APP_BASE_URL_TRIAL,
  release: process.env.TARO_APP_BASE_URL_PROD,
};
const baseURL = HostMap[envVersion];
console.log("环境", envVersion, baseURL);
function transformUrl(url) {
  if (url?.startsWith("http://") || url?.startsWith("https://")) return url;
  return baseURL + url;
}

export const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: transformUrl(options.url),
      method: options.method || "GET",
      timeout: 60000,
      data: options.data || {},
      success(res) {
        // 可以根据自己的数据状态处理响应
        if (!options.manual_err && res.data.code !== 0) {
          Taro.showToast({
            icon: "none",
            title: res.data.message || "请求失败",
            duration: 3000,
          });
          reject(new Error(res.data.message));
          return;
        }
        resolve(res.data.data);
      },
      fail(err) {
        if (!options.manual_err) {
          Taro.showToast({
            icon: "none",
            title: err.errMsg || "请求失败",
            duration: 3000,
          });
        }
        reject(err);
      },
    });
  });
};
